package light.head.controller.oa;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import light.head.constant.Msg;
import light.head.constant.Parm;
import light.head.constant.Sys;
import light.head.constant.Url;
import light.head.dao.oa.AuditStatusDAO;
import light.head.dao.oa.ProcessConfigDAO;
import light.head.dao.oa.ReimburseCategoryDAO;
import light.head.dao.oa.ReimburseDAO;
import light.head.dao.sys.MessageDAO;
import light.head.dao.sys.MessageTemplateDAO;
import light.head.dao.sys.OrganDAO;
import light.head.dao.sys.UserInfoDAO;
import light.head.enm.RESULT;
import light.head.framework.base.SupporterController;
import light.head.framework.entity.PageBean;
import light.head.model.AuditStatus;
import light.head.model.ProcessConfig;
import light.head.model.Reimburse;
import light.head.model.ReimburseCategory;
import light.head.model.ReimburseItem;
import light.head.model.UserInfo;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
/***
 * 物品申请信息
 * @author yy
 *
 */
@Controller
@RequestMapping(Url.C_REIMBURSE)
public class ReimburseController extends SupporterController{

	private ReimburseDAO reDAO;
	private ReimburseCategoryDAO rcDAO;
	private OrganDAO organDAO;
	private ProcessConfigDAO pcDAO;
	private AuditStatusDAO auDAO;
	private UserInfoDAO userDAO;
	private MessageDAO msgDAO;
	private MessageTemplateDAO mtDAO;

	@RequestMapping(value = Url.INIT)
	public ModelAndView init(HttpServletRequest request, HttpServletResponse response) throws Exception{
		return new ModelAndView(Url.REIMBURSE_INIT);
	}
	
	@RequestMapping(value = Url.QUERY)
	public ModelAndView query(HttpServletRequest request, HttpServletResponse response) throws Exception {
		PageBean pb = createPageBean(request);
		Map<String, String> map = createQueryMapByParmName(request, Parm.DELETED,Parm.TITLE, Parm.TIME1, Parm.TIME2);
		if (reDAO.findByMap_2(cu_code(request), map, pb) == RESULT.SUCCESS) {
			// 讲对应的审核状态放到对应的
			Reimburse re = null;
			for (Object o : pb.getResultList()) {
				re = (Reimburse) o;
				re.setAuditStatusList(auDAO.findByBusinessMc(Sys.B_FOUR, re.getCode()));
			}
		}
		request.setAttribute(Parm.PAGE_BEAN, pb);
		return new ModelAndView(Url.REIMBURSE_LIST);
	}
	
	@RequestMapping(value = Url.EDIT)
	public ModelAndView edit(Integer code,HttpServletRequest request, HttpServletResponse response) throws Exception{
		if(code != null){
			Reimburse re = reDAO.get(code);
			List<ReimburseItem> list = reDAO.findApplyItem(code);
			re.setItemList(list);
			request.setAttribute(Parm.REIMBURSE, re);
		}
		return new ModelAndView(Url.REIMBURSE_EDIT);
	}

	//保存申请单
	@Transactional
	@RequestMapping(value = Url.SAVE)
	public void save(Reimburse re, HttpServletRequest request, HttpServletResponse response) throws Exception {
		RESULT result = RESULT.ERROR;
		Integer oc = cu_organCode(request);
		Integer cu = cu_code(request);
		Integer rc1 =cu_roleCode(request);
		// 检查是否有可以保存的明细在保存,至少有一条明细可以保存
		if (null == re || null == re.getItemList() || re.getItemList().size() == 0) {
			print(response, Msg.PARAMETER_ERROR);
			return;
		}
		// 检查是否配置审核流程
		List<ProcessConfig> pcList = pcDAO.findByOcBusiness(organDAO.getRoot(cu_organCode(request)).getCode(), Sys.B_FOUR);
		if (pcList == null || pcList.size() == 0 ) {
			print(response, Msg.EXISTS);
			return;	
		}
		//未审核时修改
		if (re.getCode() != null && re.getPass().byteValue() == Sys.B_ONE) {
			Reimburse old = reDAO.get(re.getCode());
			old.setTotal(re.getTotal());
			old.setCapital(re.getCapital());
			old.setRemark(re.getRemark());
			old.setTitle(re.getTitle().length() > 100 ? re.getTitle().substring(0, 99) : re.getTitle());
			result = reDAO.upd(old);
			List<ReimburseItem> list = re.getItemList();
			List<ReimburseItem> oldList = reDAO.findApplyItem(re.getCode());
			
			List<ReimburseItem> newList = new ArrayList<ReimburseItem>();
			for (ReimburseItem newItem : list) {
				if(newItem.getCode() == null && newItem.getProject() != null){
					newItem.setRbc(re.getCode());
					reDAO.add(newItem);
				}
				newList.add(newItem);
				for (ReimburseItem oldItem : oldList) {
					if (newItem.getCode() != null && newItem.getCode().intValue() == oldItem.getCode().intValue() && newItem.getProject() != null) {
						oldItem.setAmount(newItem.getAmount());
						oldItem.setNum(newItem.getNum());
						oldItem.setProject(newItem.getProject());
						oldItem.setRcc(newItem.getRcc());
						oldItem.setRemark(newItem.getRemark());
						result = reDAO.upd(oldItem);
					}
				}
			}
			boolean ok = true;
			for (ReimburseItem oldItem : oldList) {
				ok = true;
				for (ReimburseItem newItem : newList) {
					if (newItem.getCode() != null && oldItem.getCode().intValue() == newItem.getCode().intValue()) {
						ok = false;
						break;
					}
				}
				if (ok) {
					reDAO.del(oldItem);
				}
			}
		// 审核不通过修改
		} else if(re.getCode() != null && re.getPass().byteValue() == Sys.B_TWO) {
			Reimburse old = reDAO.get(re.getCode());
			old.setTotal(re.getTotal());
			old.setCapital(re.getCapital());
			old.setRemark("再次提交"+ re.getRemark());
			old.setTitle(re.getTitle().length() > 100 ? re.getTitle().substring(0, 99) : re.getTitle());
			old.setPass(Sys.B_ONE);
			result = reDAO.upd(old);
			List<ReimburseItem> list = re.getItemList();
			List<ReimburseItem> oldList = reDAO.findApplyItem(re.getCode());
			
			List<ReimburseItem> newList = new ArrayList<ReimburseItem>();
			for (ReimburseItem newItem : list) {
				if(newItem.getCode() == null && newItem.getProject() != null){
					newItem.setRbc(re.getCode());
					reDAO.add(newItem);
				}
				newList.add(newItem);
				for (ReimburseItem oldItem : oldList) {
					if (newItem.getCode() != null && newItem.getCode().intValue() == oldItem.getCode().intValue() && newItem.getProject() != null) {
						oldItem.setAmount(newItem.getAmount());
						oldItem.setNum(newItem.getNum());
						oldItem.setProject(newItem.getProject());
						oldItem.setRcc(newItem.getRcc());
						oldItem.setRemark(newItem.getRemark());
						result = reDAO.upd(oldItem);
					}
				}
			}
			boolean ok = true;
			for (ReimburseItem oldItem : oldList) {
				ok = true;
				for (ReimburseItem newItem : newList) {
					if (newItem.getCode() != null && oldItem.getCode().intValue() == newItem.getCode().intValue()) {
						ok = false;
						break;
					}
				}
				if (ok) {
					reDAO.del(oldItem);
				}
			}
			//重修提交申请
			List<AuditStatus> auList = auDAO.findByBusinessMc(Sys.B_FOUR, re.getCode());
			for (AuditStatus auditStatus : auList) {
				auDAO.del(auditStatus);
			}
			int i = 1;
			for (ProcessConfig pc : pcList) {
				
				AuditStatus au = new AuditStatus();
				au.setBusiness(Sys.B_FOUR);
				au.setCt(new Date());
				au.setCu(cu);
				au.setOc(oc);
				au.setMc(re.getCode());
				au.setRc(pc.getRc());
				au.setPcc(pc.getCode());
				au.setPc(pc.getPc());
				// 默认第一个审核节点的上一节点审核状态为1通过
				if (null != pc.getPc() && pc.getPc().intValue() == 1) {
					au.setBeforeStatus(Sys.B_ONE);
				}
				if (null != pc.getPc() && pc.getPc().intValue() == 1 && null != rc1 && pc.getRc() == rc1){
					au.setStatus(Sys.B_ONE);
					au.setAt(new Date());
					au.setAu(cu);
					i++;
				}
				if (null != pc.getPc() && pc.getPc().intValue() == 2 && i == 2) {
					au.setBeforeStatus(Sys.B_ONE);
				}
				result = auDAO.add(au);
			}
			// 消息通知审核人
			Integer rc = auDAO.findByBusinessOcMc(Sys.B_FOUR, oc, re.getCode());	// 获取该机构具有审核申请单的角色编号
			if (null != rc) {
				List<UserInfo> userList = userDAO.findByRoleRc(oc, rc);	// 获取有审核角色的所有用户
				List<Integer> rucs = new ArrayList<Integer>();
				for (UserInfo u : userList) {
					rucs.add(u.getCode());
				}
				String content = mtDAO.applyTofirst(old, cu_realName(request));
				msgDAO.sendToUsers("【" + cu_realName(request) + "】提交申请待审核通知", content, cu_code(request), cu_organCode(request), rucs);
			}
		} else if(re.getCode() == null) {
			re.setCu(cu);
			re.setOc(oc);
			if (re.getTitle().length() > 100)
			re.setTitle(re.getTitle().substring(0, 99));
			re.setDeleted(false);
			re.setPass(Sys.B_ONE);
			re.setCt(new Date());
			result = reDAO.add(re);
			for (ReimburseItem item : re.getItemList()) {
				item.setRbc(re.getCode());
				result = reDAO.add(item);
			}
			int i = 1;
			for (ProcessConfig pc : pcList) {
				AuditStatus au = new AuditStatus();
				au.setBusiness(Sys.B_FOUR);
				au.setCt(new Date());
				au.setCu(cu);
				au.setOc(oc);
				au.setMc(re.getCode());
				au.setRc(pc.getRc());
				au.setPcc(pc.getCode());
				au.setPc(pc.getPc());
				// 默认第一个审核节点的上一节点审核状态为1通过
				if (null != pc.getPc() && pc.getPc().intValue() == 1) {
					au.setBeforeStatus(Sys.B_ONE);
				}
				//判断申请人为审核人时自动审核通过
				if (null != pc.getPc() && pc.getPc().intValue() == 1 && null != rc1 && pc.getRc() == rc1){
					au.setStatus(Sys.B_ONE);
					au.setAt(new Date());
					au.setAu(cu);
					i++;
					Reimburse r = reDAO.get(re.getCode());
					re.setPass(Sys.B_FOUR);
					reDAO.upd(r);
				}
				if (null != pc.getPc() && pc.getPc().intValue() == 2 && i == 2) {
					au.setBeforeStatus(Sys.B_ONE);
				}
				result = auDAO.add(au);
			}
			
			// 消息通知审核人
			Integer rc = auDAO.findByBusinessOcMc(Sys.B_FOUR, oc, re.getCode());	// 获取该机构具有审核申请单的角色编号
			if (null != rc) {
				List<UserInfo> userList = userDAO.findByRoleRc(oc, rc);	// 获取有审核角色的所有用户
				List<Integer> rucs = new ArrayList<Integer>();
				for (UserInfo u : userList) {
					rucs.add(u.getCode());
				}
				String content = mtDAO.applyTofirst(re, cu_realName(request));
				msgDAO.sendToUsers("【" + cu_realName(request) + "】提交申请待审核通知", content, cu_code(request), cu_organCode(request), rucs);
			}
		}
		if(result == RESULT.SUCCESS){
			print(response, Msg.SUCCESS);
		}else{
			print(response, Msg.ERROR);
			return;
		}
	}
	

	@RequestMapping(value = Url.SHIELD)
	public void shield(HttpServletRequest request, HttpServletResponse response) throws Exception {
		String code = request.getParameter(Parm.CODE);
		if (!isNotNull(code)) {
			print(response, Msg.PARAMETER_ERROR);
			return;
		}
		Reimburse re = reDAO.get(Integer.parseInt(code));
		if (re == null) {
			print(response, Msg.NOT_FIND);
		} else {
			re.setDeleted(true);
			if (reDAO.upd(re) == RESULT.SUCCESS) {
				print(response, Msg.SUCCESS);
			} else {
				print(response, Msg.ERROR);
			}
		}
	}
	
	
	@RequestMapping(value = Url.UN_SHIELD)
	public void unshield(HttpServletRequest request, HttpServletResponse response) throws Exception {
		String code = request.getParameter(Parm.CODE);
		if (!isNotNull(code)) {
			print(response, Msg.PARAMETER_ERROR);
			return;
		}
		Reimburse re = reDAO.get(Integer.parseInt(code));
		if (re == null) {
			print(response, Msg.NOT_FIND);
		} else {
			re.setDeleted(false);
			if (reDAO.upd(re) == RESULT.SUCCESS) {
				print(response, Msg.SUCCESS);
			} else 
				print(response, Msg.ERROR);
		}
	}
	
	// 单个申请单详情
	@RequestMapping(value = Url.DETAIL)
	public ModelAndView detail(Integer code, HttpServletRequest request, HttpServletResponse response) throws Exception {
		if (null != code) {
			Reimburse a = reDAO.get(code);
			if (null != a) {
				a.setAuditStatusList(auDAO.findByBusinessMc(Sys.B_FOUR, a.getCode()));
				List<ReimburseItem> list = reDAO.findApplyItem(code);
				a.setItemList(list);
				request.setAttribute(Parm.REIMBURSE, a);
			}
		}
		return new ModelAndView(Url.REIMBURSE_DETAIL);
	}
	/**
	 * 查询类别
	 */
	@RequestMapping(Url.AID_INIT)
	public ModelAndView aidInit(HttpServletRequest request, HttpServletResponse response) throws Exception {
		request.setAttribute(Parm.INDEX, request.getParameter(Parm.INDEX));
		System.out.println(request.getParameter(Parm.INDEX));
		return new ModelAndView(Url.REIMBURSE_TYPEINIT);
	}
	
	@RequestMapping(Url.AID_LIST)
	public ModelAndView aidList(HttpServletRequest request, HttpServletResponse response) throws Exception {
		PageBean pb = createPageBean(request);
		Map<String, String> map = createQueryMapByParmName(request, Parm.NAME, Parm.DELETED, Parm.OC);
		Integer oc  =organDAO.getRoot(cu_organCode(request)).getCode();
		rcDAO.findByMapOc(organDAO.getSonCodeList(oc), map, pb);
		request.setAttribute(Parm.PAGE_BEAN, pb);
		return new ModelAndView(Url.REIMBURSE_TYPELIST);
	}
	@RequestMapping(Url.AID_EDIT)
	public ModelAndView aidEdit(HttpServletRequest request, HttpServletResponse response) throws Exception {
		return new ModelAndView(Url.REIMBURSE_TYPEEDIT);
	}
	// 添加类别
	@RequestMapping("add")
	public void add(ReimburseCategory rc,HttpServletRequest request, HttpServletResponse response) throws Exception {
		if (rc == null) return;
		RESULT result = RESULT.ERROR;
		rc.setCt(new Date());
		rc.setCu(cu_code(request));
		rc.setOc(cu_organCode(request));
		result = rcDAO.add(rc);
		if (RESULT.SUCCESS == result) {
			print(response, Msg.SUCCESS);
		} else
			print(response, Msg.ERROR);
	}
	@Autowired
	public void setReDAO(ReimburseDAO reDAO) {
		this.reDAO = reDAO;
	}
	
	@Autowired
	public void setOrganDAO(OrganDAO organDAO) {
		this.organDAO = organDAO;
	}

	@Autowired
	public void setPcDAO(ProcessConfigDAO pcDAO) {
		this.pcDAO = pcDAO;
	}
	@Autowired
	public void setAuDAO(AuditStatusDAO auDAO) {
		this.auDAO = auDAO;
	}
	@Autowired
	public void setUserDAO(UserInfoDAO userDAO) {
		this.userDAO = userDAO;
	}
	@Autowired
	public void setMsgDAO(MessageDAO msgDAO) {
		this.msgDAO = msgDAO;
	}
	@Autowired
	public void setMtDAO(MessageTemplateDAO mtDAO) {
		this.mtDAO = mtDAO;
	}
	@Autowired
	public void setRcDAO(ReimburseCategoryDAO rcDAO) {
		this.rcDAO = rcDAO;
	}
	

}
